<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公司名称" prop="companyId">
        <treeselect v-model="queryParams.companyId" :options="deptOptions" placeholder="请选择公司" :show-count="true" style="width: 160px"  clearable/> 
      </el-form-item>
      <el-form-item label="文件名" prop="analysisFileName">
        <el-input
          v-model="queryParams.analysisFileName"
          placeholder="请输入报告文件名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeAnalysisCreateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
         type="daterange" 
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['oil:analysis:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['oil:analysis:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['oil:analysis:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['oil:analysis:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="analysisList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="公司名称" align="center" prop="companyName" />
      <el-table-column label="开始日期" align="center" prop="analysisBeginTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.analysisBeginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="截止时间" align="center" prop="analysisEndTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.analysisEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="analysisCreateTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.analysisCreateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createUserName" />
      <el-table-column label="更新人" align="center" prop="updateUserName" />
      <el-table-column label="文件名" align="center" prop="analysisFileName" />
      <el-table-column label="更新时间" align="center" prop="analysisUpdateTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.analysisUpdateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['oil:analysis:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            title="附件下载"
            icon="el-icon-download"
            @click="downloadAnalysis(scope.row)"
            v-hasPermi="['oil:analysis:download']"
          >下载</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['oil:analysis:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加新增油液分析报告弹窗 -->
    <el-dialog
      title="新增分析报告"
      :visible.sync="oilReportDialogVisible"
      width="80%"
      :show-close="false"
      append-to-body
      v-loading="saveLoading"  
      element-loading-text="处理中..."  
      element-loading-spinner="el-icon-loading"  
      element-loading-background="rgba(0, 0, 0, 0.5)"  
    >
    <div class="editor-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <!-- 公司名称 + 设备名称 一行两列 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="公司名称" prop="companyId">
            <treeselect v-model="form.companyId" :options="deptOptions" placeholder="请选择公司" :show-count="true" style="width: 100%"  clearable/> 
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 开始时间与结束时间 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开始时间" prop="analysisBeginTime">
            <el-date-picker
              v-model="form.analysisBeginTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择开始时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="analysisEndTime">
            <el-date-picker
              v-model="form.analysisEndTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择结束时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 富文本编辑器 -->
    <div v-if="!saveLoading"  ref="editorElem" class="editor" style="margin-top: 5px;"></div>

    <!-- 按钮 -->
    <div class="buttons">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <!-- <el-button @click="oilReportDialogVisible = false">取消</el-button> -->
      <el-button @click="handleCancel">取消</el-button>
    </div>
  </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAnalysis, getAnalysis, delAnalysis, addAnalysis, updateAnalysis, uploadBookFile } from "@/api/oil/analysis";
// import { listDevice } from "@/api/oil/device";
import { deptTreeSelect } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import E from 'wangeditor';
import htmlDocx from 'html-docx-js/dist/html-docx';
import { saveAs } from 'file-saver';


export default {
  name: "Analysis",
  components: { Treeselect },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      analysisList: [],
      title: "",
      open: false,
      daterangeAnalysisCreateTime: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        createUserName: null,
        updateUserName: null,
        analysisFileName: null,
        analysisFileContext: null,
        analysisBeginTime: null,
        analysisEndTime: null,
        analysisTempId: null,
        analysisTypeId: null,
        analysisCreateTime: null,
        analysisUpdateTime: null
      },
      form: {
      },
      deviceOptions: [],
      rules: {
        companyId: [{ required: true, message: '请选择公司', trigger: 'blur' }],
        analysisBeginTime: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
        analysisEndTime: [{ required: true, message: '请选择结束时间', trigger: 'blur' }]
      },
      editor: null,
      deptOptions: [],
      fileList: [],
      isFileAdded: false,
      oilReportDialogVisible: false,
      initialOilReportData: null,
      saveLoading: false, // 保存操作的加载状态
      // 添加默认富文本内容
      defaultRichTextContent: '<html><head><title></title></head><body><br/><br/><p style="text-align:left;"><font face="宋体" size="3"><b>报告编号：XXXX-XX</b></font></p><p style="text-align:center;"><font face="宋体" size="5"><b>XX公司</b></font></p><p style="text-align:center;"><b><font size="6" face="宋体">设备磨损与润滑油状态</font></b></p><p style="text-align:center;"><font face="宋体" size="6" style=""><b>数据分析报告</b></font></p><p style="text-align:center;"><font face="宋体" size="6" style=""><b><br></b></font></p><p style="text-align:center;"><font face="宋体" size="6" style=""><b><br></b></font></p><p style="text-align:center;"><font face="宋体" size="6" style=""><b><br></b></font></p><p style="text-align:center;"><font face="宋体" size="6" style=""><b><br></b></font></p><p style="text-align:center;"><font size="5"><b>编制：</b>XXX</font></p><p style="text-align:center;"><font size="5"><b>审查：</b>XXX</font></p><p style="text-align:center;"><font size="5"><b>批准：</b>XXX</font></p><p style="text-align:center;"></p><p style="text-align:center;"></p><br><br><br><br><br><br><p style="text-align:center;"><font size="5"><b>中信重工机械股份有限公司</b></font></p><p style="text-align:center;"><font size="5"><b>河南省智能矿山装备与工艺创新中心</b></font></p><p style="text-align:center;"><font size="5"><b>XXXX年XX月XX日</b></font></p><br clear=all style="page-break-before:always" /><h1><!--[if-->一、<!--[endif]--><b>注意事项</b></h1><p style="padding-left:2em; text-indent: 2em;"><font size="3">1、本报告无分析内容、无审查、批准人签字无效；</font></p><p style="padding-left:2em; text-indent: 2em;"><font size="3">2、本报告涂改无效，分析结果仅对本次数据有效；</font></p><p style="padding-left:2em; text-indent: 2em;"><font size="3">3、未经本公司书面许可，部分复制、摘用或篡改本报告内容，引起法律纠纷，责任自负；</font></p><p style="padding-left:2em; text-indent: 2em;"><font size="3">4、若对报告有异议，请于收到报告之日起一周内向本公司提出，逾期不再受理；</font></p><p style="padding-left:2em; text-indent: 2em;"><font size="3">5、免责条款</font></p><ul><li><font size="3">本公司仅作为客户在线监测系统安装、调试及监测设备的维护、服务咨询等相关工作，并根据客户需求对监测设备提供参考性的故障诊断处理意见；</font></li><li><font size="3">针对监测设备采取的任何措施，如停机、维修、更换均由客户自己决定；</font></li><li><font size="3">本公司不承担因监测设备中断或其他原因引起的任何损失、损坏和人员伤害。</font></li></ul><p><br></p><br clear=all style="page-break-before:always" /><h1><!--[if-->二、<!--[endif]--><b>背景介绍</b></h1><p style="padding-left:2em; text-indent: 2em;"><font size="3">本次主要分析XX公司现场X台油液监测设备对润滑油的监测数据情况，包括XX。本次报告数据分析时段为：XXXX年XX月XX日至XXXX年XX月XX日。</font></p><p style="padding-left:2em; text-indent: 2em;"><font size="3">主要分析的监测数据有：油液中的含水量、水活性、粘度、介电常数、温度、颗粒度等。</font></p><h1><!--[if-->三、<!--[endif]--><b>油液质量评价及用油建议</b></h1><div style="text-align:center;"> 用油建议</div><p><br></p><h1><!--[if-->四、<!--[endif]--><b>数据分析过程</b></h1><h3><!--[if-->1、&nbsp;<!--[endif]--><b>XX</b></h3><h4><!--[if--><font size="3">（1）&nbsp;<!--[endif]-->粘度温度分析</font></h4><h4><!--[if--><font size="3">（2）&nbsp;<!--[endif]-->密度和介电常数分析</font></h4><h4><!--[if--><font size="3">（3）&nbsp;<!--[endif]-->颗粒度分析</font></h4><p><br></p><br clear=all style="page-break-before:always" /><h1><b>附录：河南省智能矿山装备与工艺创新中心介绍</b></h1><p style="text-indent: 2em;"><font size="3">河南省智能矿山装备与工艺创新中心是由中信重工机械股份有限公司牵头、联合洛阳栾川钼业集团股份有限公司、中信云网有限公司等28家单位共同申报的河南省制造业创新中心，于2022&nbsp;年&nbsp;4&nbsp;月正式进入河南省第四批制造业创新中心培育单位名单，2023年&nbsp;12月通过现场考核论证，正式认定为河南省制造业创新中心。</font></p><p style="text-indent: 2em;"><font size="3">创新中心以行业发展趋势为导向，以矿山装备制造龙头企业为核心，以互联网+先进制造和服务为途径，通过整合产业链上下游优势资源，依靠协同创新突破产业核心技术，致力于形成面向矿山行业的关键共性技术创新中心、科技综合服务中心、技术成果孵化转化基地、人才培养建设基地，最终形成国际一流的矿山行业智能装备与工艺技术创新中心和创新产业发展联盟。</font></p><p style="text-indent: 2em;"><font size="3">目前创新中心围绕破碎机、高压辊磨机、球磨机等矿山核心主机装备和工艺单元，研发智能传感和控制关键共性技术；搭建行业内领先的矿山装备工业互联网平台，实现矿山装备数据从监测、传输、存储、分析的全流程功能；开发了矿山装备健康度在线监测和故障检测系统、油液在线监测系统、振动在线监测系统、设备全生命周期管理系统等智能运维系统和产品，实现产业化、规模化生产。</font></p><p style="text-indent: 2em;"><font size="3">创新中心以当下的业务情况为基础，充分发掘矿山装备数据价值，提升矿山装备数字化、智能化水平，实现矿山装备健康状态监测、预测性维护和管理，以及矿山装备的故障诊断，促进用户现场的设备精益化管理，进一步提升客户设备管理能力、保障设备稳定运行、提供数据支撑，从而助力客户实现智能制造和智能管理，为用户创造实际经济效益。</font></p></body></html>' 
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  watch: {
    oilReportDialogVisible(val) {
      if (val) {
        this.$nextTick(() => {
          if (this.$refs.editorElem) {
            try {
              if (this.editor) {
                this.editor.destroy();
              }
              this.editor = new E(this.$refs.editorElem);
              // 启用 Base64 插入图片
              this.editor.config.uploadImgShowBase64 = true; 
              this.editor.config.uploadImgMaxSize = 500 * 1024 * 1024; // 设置上传最大尺寸
              this.editor.config.uploadImgTimeout = 5000; // 设置超时

              // 自定义菜单栏，增加更多字号选项
              this.editor.config.menus = [
                'head',  // 标题
                'bold',  // 粗体
                'fontSize',  // 字号
                'fontName',  // 字体
                'italic',  // 斜体
                'underline',  // 下划线
                'strikeThrough',  // 删除线
                'foreColor',  // 文字颜色
                'backColor',  // 背景颜色
                'link',  // 插入链接
                'list',  // 列表
                'justify',  // 对齐方式
                'quote',  // 引用
                'emoticon',  // 表情
                'image',  // 插入图片
                'table',  // 插入表格
                'video',  // 插入视频
                'code',  // 插入代码
                'undo',  // 撤销
                'redo'   // 重做
              ];
              // 增加更多字号选项
              const fontSizeConfig = {};
                        for (let size = 10; size <= 48; size++) {
                            fontSizeConfig[`size-${size}`] = { name: `${size}px`, value: `${size}px` };
                        }

                        // 设置字号配置
                        this.editor.config.fontSizes = fontSizeConfig;

              // 开启表格合并单元格功能
              this.editor.config.showTableMenu = true;
              this.editor.config.showTableDropdown = true;

              this.editor.create();

              // if (this.initialOilReportData?.reportContent) {
              //   this.editor.txt.html(this.initialOilReportData.reportContent);
              // }
               // 根据操作类型设置富文本内容
               let content = this.initialOilReportData?.reportContent || this.defaultRichTextContent;
              this.editor.txt.html(content);
            } catch (error) {
              console.error('富文本编辑器初始化失败:', error);
            }
          }
        });
      } else if (this.editor) {
        this.editor.destroy();
      }
    }
  },
  methods: {
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeAnalysisCreateTime && '' != this.daterangeAnalysisCreateTime) {
        this.queryParams.params["beginAnalysisCreateTime"] = this.daterangeAnalysisCreateTime[0];
        this.queryParams.params["endAnalysisCreateTime"] = this.daterangeAnalysisCreateTime[1];
      }
      listAnalysis(this.queryParams).then(response => {
        this.analysisList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        companyId: null,
        companyName: null,
        createUserId: null,
        createUserName: null,
        updateUserId: null,
        updateUserName: null,
        analysisCheckUserId: null,
        analysisFileName: null,
        analysisFileContext: null,
        analysisFilePath: null,
        analysisBeginTime: null,
        analysisEndTime: null,
        analysisTempId: null,
        analysisTypeId: null,
        analysisCreateTime: null,
        analysisUpdateTime: null,
        device: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.daterangeAnalysisCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length!== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.title = "新增分析报告";
      this.initialOilReportData = null; // 新增时清空初始数据
      this.oilReportDialogVisible = true;
    },
    handleUpdate(row) {
      const id = row.id || this.ids;
      getAnalysis(id).then(response => {
        console.log('获取到的富文本内容:', response.data.analysisFileContext); // 打印内容进行检查
        
        
        this.initialOilReportData = {
          id: response.data.id,
          companyId: response.data.companyId,
          companyName: response.data.companyName, 
          createUserId: response.data.createUserId,
          createUserName: response.data.createUserName,
          updateUserId: response.data.updateUserId,
          updateUserName: response.data.updateUserName,
          analysisCheckUserId: response.data.analysisCheckUserId,
          analysisFileName: response.data.analysisFileName,
          analysisFileContext: response.data.analysisFileContext,
          analysisFilePath: response.data.analysisFilePath, 
          analysisBeginTime: response.data.analysisBeginTime,
          analysisEndTime: response.data.analysisEndTime,
          analysisTempId: response.data.analysisTempId,
          analysisTypeId: response.data.analysisTypeId,
          analysisCreateTime: response.data.analysisCreateTime,
          analysisUpdateTime: response.data.analysisUpdateTime,
          reportContent: response.data.analysisFileContext
        };
        this.form = {
          id: response.data.id,
          companyId: response.data.companyId,
          companyName: response.data.companyName,          
          createUserId: response.data.createUserId,
          createUserName: response.data.createUserName,          
          updateUserId: response.data.updateUserId,
          updateUserName: response.data.updateUserName,             
          analysisCheckUserId: response.data.analysisCheckUserId,
          analysisFileName: response.data.analysisFileName,
          analysisFileContext: response.data.analysisFileContext,          
          analysisFilePath: response.data.analysisFilePath,
          analysisBeginTime: response.data.analysisBeginTime,
          analysisEndTime: response.data.analysisEndTime,
          analysisTempId: response.data.analysisTempId,
          analysisTypeId: response.data.analysisTypeId,
          analysisCreateTime: response.data.analysisCreateTime,
          analysisUpdateTime: response.data.analysisUpdateTime,
          device: response.data.device
        };
         this.oilReportDialogVisible = true;
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除相关数据项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delAnalysis(ids).then(() => {
          this.getList();
          this.$message.success("删除成功");
        });
      }).catch(() => {});
    },
    handleExport() {
      this.download('oil/analysis/export', {
        ...this.queryParams
      }, `分析报告_${new Date().getTime()}.xlsx`);
    },
    handleSave() {
  this.$refs.form.validate((valid) => {
    if (valid) {
      // 获取富文本编辑器内容
      this.form.analysisFileContext = this.editor.txt.html();
      if (this.form.id) {
        // 更新操作
        updateAnalysis(this.form)
          .then(() => {
            this.$message({
              type: 'success',
              message: '更新成功'
            });
            this.oilReportDialogVisible = false;
            this.getList(); // 重新获取列表数据
          })
          .catch(error => {
            console.error('更新失败:', error);
            this.$message({
              type: 'error',
              message: '更新失败'
            });
          });
      } else {
        // 新增操作
        this.saveLoading = true;
        addAnalysis(this.form)
          .then(() => {
            this.$message({
              type: 'success',
              message: '新增成功'
            });
            this.saveLoading = false;
            this.oilReportDialogVisible = false;
            this.getList(); // 重新获取列表数据
          })
          .catch(error => {
            console.error('新增失败:', error);
            this.$message({
              type: 'error',
              message: '新增失败'
            });
          });
      }
    } else {
      console.log('error submit!!');
      return false;
    }
  });
},
    downloadAnalysis(row) {

      getAnalysis(row.id).then(response => {
        const htmlContent = response.data.analysisFileContext;
        console.log(htmlContent);
        // 使用 html-docx-js 将 HTML 转换为 Word 文档的二进制数据
        const wordBlob = htmlDocx.asBlob(htmlContent);
        // 保存 Word 文档
        saveAs(wordBlob, `${response.data.analysisFileName}`);
      }).catch(error => {
        console.error('下载失败:', error);
      });
    },
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    handleCancel() {
      // 关闭弹窗
      this.oilReportDialogVisible = false;
      // 清除富文本内容（如果已初始化）
      if (this.editor) {
        this.editor.txt.clear();
      }
      // 清空初始数据
      this.initialOilReportData = {};
      this.form.companyId = '';
      this.form.analysisBeginTime = '';
      this.form.analysisEndTime = '';
      this.form.analysisFileContext = '';
    }
  }
};
</script>
<style scoped>
.editor-container {
  padding: 10px;
}
.buttons {
  margin-top: 20px;
}
/* .editor {
  border: 1px solid #ccc;
  min-height: 400px;
  height: auto;
} */

</style>    